﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IFRS.Web;
using IFRS.Models;
using IFRS.DataAccess.DAL;
using System.Data;
using IFRS_Global;
using System.Globalization;
using System.Threading;

public partial class IFRS_WIN02_4A : PageBase
{
    #region "---------- Events -----------"
    protected void Page_Load(object sender, EventArgs e)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        if (!(Page.IsPostBack || Page.IsCallback))
        {            
            this.AddClientScript();
            this.ViewMenu();
            this.BindDDL();
            this.SetErrorMessage();            
            if (Request.QueryString["id"] != null)
            {
                this.BindData(Convert.ToInt32(Request.QueryString["id"].ToString()));
            }
            this.SetDefaultData();
        }
        else
            ClientScript.RegisterHiddenField("isPostBack", "1");
    }
    protected void btnSAVE_NEW_Click(object sender, EventArgs e)
    {
        SaveData(true);
    }
    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        SaveData(false);
    }
    protected void btnCANCEL_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IFRS/WIN02_1S.aspx");
    }
    protected void btnCLEAR_Click(object sender, EventArgs e)
    {
        Response.Redirect(ResolveUrl(Request.Url.AbsolutePath));
    }
    #endregion
    #region "---------- Methods -----------"
    private void AddClientScript()
    {
        btnCANCEL.Attributes["OnClick"] = "if(!confirm(\"" + Resources.ifrsResource.ConfirmCancel + "\")) return false;";

        btnGLAccountCode.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount.aspx") + "','700','550');");
        btnCostCenter.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/CostCenter.aspx") + "','700','550');");        
        btnReferenceInterestCD.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/ReferenceInterest.aspx") + "','700','550');");
        btnCurrencyCode.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/Currency.aspx") + "','700','550');");
        btnCustomer.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/Customer.aspx") + "','700','550');");
        btnLoanObjective.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/VmLoanObjective.aspx") + "','700','550');");        
        
        txtGLAccountCode.AddControl(hidGLAccountCode.ClientID);
        txtGLAccountCode.AddControl(txtGLAccountCode.ClientID);
        txtGLAccountCode.ControlSearch = txtGLAccountCode.ClientID;
        txtGLAccountCode.AddQueryString("bIsActive", "1");
        txtGLAccountCode.SearchKey = "GLAccount_oGLAccountCode_oGLAccountName";

        txtCostCenter.AddControl(hidCostCenter.ClientID);
        txtCostCenter.AddControl(txtCostCenter.ClientID);
        txtCostCenter.ControlSearch = txtCostCenter.ClientID;
        txtCostCenter.AddQueryString("bIsActive", "1");
        txtCostCenter.SearchKey = "VWCostCenter_oCOST_CENTER_CD_oCOST_CENTER_NM";

        txtReferenceInterestCD.AddControl(hidReferenceInterestCD.ClientID);
        txtReferenceInterestCD.AddControl(txtReferenceInterestCD.ClientID);
        txtReferenceInterestCD.ControlSearch = txtReferenceInterestCD.ClientID;
        txtReferenceInterestCD.SearchKey = "ReferenceInterest_oReferenceInterestCD_oReferenceInterestNM";

        txtCurrencyCode.AddControl(hidCurrencyCode.ClientID);
        txtCurrencyCode.AddControl(txtCurrencyCode.ClientID);
        txtCurrencyCode.ControlSearch = txtCurrencyCode.ClientID;
        txtCurrencyCode.AddQueryString("bIsActive", "1");
        txtCurrencyCode.SearchKey = "Currency_oCurrencyCode_oCurrencyName";
        
        txtCustomer.AddControl(hidCustomer.ClientID);
        txtCustomer.AddControl(txtCustomer.ClientID);
        txtCustomer.ControlSearch = txtCustomer.ClientID;
        txtCustomer.AddQueryString("bIsActive", "1");
        txtCustomer.SearchKey = "Customer_oCustomerID_oCustomerCode";
        
        txtLoanObjective.AddControl(hidLoanObjective.ClientID);
        txtLoanObjective.AddControl(txtLoanObjective.ClientID);
        txtLoanObjective.ControlSearch = txtLoanObjective.ClientID;
        txtLoanObjective.AddQueryString("bIsActive", "1");
        txtLoanObjective.SearchKey = "VmLoanObjective_oCBT_CUST_BUSINESS_TYPE_ID_oCBT_DESC_LEV1";
    }
    private void BindData(int ID)
    {
        List<ManualLoan> manualLoan = new List<ManualLoan>();
        DataTable dt = new SPR_MANUAL_LOAN().SEARCH_BYID(ID);
        if (dt.Rows.Count > 0)
        {
            ConvertHelper.ConvertDataTableToObject(dt, manualLoan);

            txtTransactionDate.Text = DateTime.Now.DateToString();            
            txtAccountNo.Text = manualLoan[0].AccountNo;
            txtGLAccountCode.Text = manualLoan[0].GLAccount;
            txtCostCenter.Text = manualLoan[0].CostCenterName;
            txtStartDate.Text = manualLoan[0].StartedDate.DateToString();
            txtEndDate.Text = manualLoan[0].EndDate.DateToString();
            txtLastPayDate.Text = manualLoan[0].LastPayDate.DateToString();
            txtNextPayDate.Text = manualLoan[0].NextPayDate.DateToString(); 
            txtPaymentFreq.Text = manualLoan[0].PaymentFreq.ToString();
            ddlPaymentFreqTimeBase.SelectedValue = manualLoan[0].PaymentFreqTimeBase;
            ddlPaymentCondition.SelectedValue = manualLoan[0].PaymentConditionID.ToString();
            ddlCalInterestCond.Text = manualLoan[0].CalInterestCondID.ToString();
            ddlInterestType.Text = manualLoan[0].InterestTypeID.ToString();
            txtInterestRate.Text = manualLoan[0].InterestRate.ToString();
            txtReferenceInterestCD.Text = manualLoan[0].RefInterestName;
            txtAdditionalInterest.Text = manualLoan[0].AdditionalInterest.ToString();
            ddlDayCountMethod.Text = manualLoan[0].DayCountMethodID.ToString();
            txtCurrencyCode.Text = manualLoan[0].CurrencyCode;
            txtUnpaidInterest.Text = manualLoan[0].UnpaidInterest.ToString();
            txtDept.Text = manualLoan[0].Dept.ToString();
            ddlCreditLevel.Text = manualLoan[0].CreditLevelID.ToString();
            txtCustomer.Text = manualLoan[0].CustomerCode;
            ddlContractLoanType.SelectedValue = manualLoan[0].ContractLoanTypeID.ToString();
            txtLoanObjective.Text = manualLoan[0].LoanObjectiveName;
            txtFirstMisDate.Text = manualLoan[0].FisrtMisDate.DateToString();
            chkAdjustFlag.Checked = manualLoan[0].AdjustFlag == "Y" ? true : false;
            txtReservedAmount.Text = manualLoan[0].ReservedAmount.ToString();
            txtApprovedAmount.Text = manualLoan[0].ApprovedAmount.ToString();
            txtStatus.Text = "สร้างรายการ";         

            hidManualLoanID.Value = manualLoan[0].ManualLoanID.ToString();
            hidUpdateDate.Value = manualLoan[0].UpdatedDate.ToString();

            
            hidCostCenter.Value = manualLoan[0].CostCenter;
            hidGLAccountCode.Value = manualLoan[0].GLAccount;
            hidReferenceInterestCD.Value = manualLoan[0].RefInterestCode;
            hidCurrencyCode.Value = manualLoan[0].CurrencyCode;
            hidCustomer.Value = manualLoan[0].CustomerID.ToString();
            hidLoanObjective.Value = manualLoan[0].LoanObjectiveID;
        }
    }
    private void BindDDL()
    {
        ddlPaymentFreqTimeBase.SetData(DDL_TYPE.PaymentFrequencyTimeBase, "", false, true);
        ddlPaymentCondition.SetData(DDL_TYPE.PaymentCondition, "", false, true);
        ddlCalInterestCond.SetData(DDL_TYPE.CalInterestCond, "", false, true);
        ddlInterestType.SetData(DDL_TYPE.InterestType, "", false, true);
        ddlDayCountMethod.SetData(DDL_TYPE.DayCountMethod, "", false, true);
        ddlCreditLevel.SetData(DDL_TYPE.CreditLevel, "", false, true);
        ddlContractLoanType.SetData(DDL_TYPE.ContractLoanType, "", false, true);        
        txtStatus.Text = "สร้างรายการ";
    }    
    private void SetDefaultData()
    {
        txtStatus.Text = "สร้างรายการ";
        txtCurrencyCode.Text = "THB";
        hidCurrencyCode.Value = "THB";        
    }
    private void SetErrorMessage()
    {
        btnSAVE.ValidationGroup = "Master";
        btnSAVE_NEW.ValidationGroup = "Master";
        reqTransactionDate.SetRequiredField(lblTransactionDate, txtTransactionDate, btnSAVE);
        reqAccountNo.SetRequiredField(lblAccountNo, txtAccountNo, btnSAVE);
        reqGLAccountCode.SetRequiredField(lblGLAccountCode, txtGLAccountCode, btnSAVE);
        reqCostCenter.SetRequiredField(lblCostCenter, txtCostCenter, btnSAVE);
        reqLastPayDate.SetRequiredField(lblLastPayDate, txtLastPayDate, btnSAVE);
        reqNextPayDate.SetRequiredField(lblNextPayDate, txtNextPayDate, btnSAVE);
        reqInterestType.SetRequiredField(lblInterestType, ddlInterestType, btnSAVE);
        reqCurrencyCode.SetRequiredField(lblCurrencyCode, txtCurrencyCode, btnSAVE);
        reqDept.SetRequiredField(lblDept, txtDept, btnSAVE);
        reqCreditLevel.SetRequiredField(lblCreditLevel, ddlCreditLevel, btnSAVE);
        reqCustomer.SetRequiredField(lblCustomer, txtCustomer, btnSAVE);
        reqContractLoanType.SetRequiredField(lblContractLoanType, ddlContractLoanType, btnSAVE);
        reqLoanObjective.SetRequiredField(lblLoanObjective, txtLoanObjective, btnSAVE);
    }
    private void SaveData(bool SaveNew)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtStartDate.Text) && !string.IsNullOrEmpty(txtEndDate.Text))
            {
                if (!ValidationDateNotEqual(txtStartDate.Text.StringToDate(), txtEndDate.Text.StringToDate()))
                {
                    JS_Alert(string.Format("{0} {1} {2}", lblEndDate.Text, Resources.ifrsResource.Must + Resources.ifrsResource.Over, lblStartDate.Text));
                    return;
                }
            }
            if (!ValidationDateNotEqual(txtLastPayDate.Text.StringToDate(), txtNextPayDate.Text.StringToDate()))
            {
                JS_Alert(string.Format("{0} {1} {2}", lblNextPayDate.Text, Resources.ifrsResource.Must + Resources.ifrsResource.Over, lblLastPayDate.Text));
                return;
            }
            if (ddlInterestType.SelectedValue == Resources.ifrsResource.InterestType_FloatingRate) // อัตราลอยตัว
            {
                if (string.IsNullOrEmpty(this.txtReferenceInterestCD.Text) || string.IsNullOrEmpty(hidReferenceInterestCD.Value))
                {
                    JS_Alert(string.Format("{0}", Resources.ifrsResource.MustInputRefInterestCode));
                    return;
                }
            }

            ManualLoan manualLoan = new ManualLoan();

            manualLoan.TransactionDate = txtTransactionDate.Text.StringToDateAllowNull();
            manualLoan.AccountNo = txtAccountNo.Text;
            manualLoan.GLAccount = txtGLAccountCode.Text;
            manualLoan.CostCenter = hidCostCenter.Value;
            manualLoan.StartedDate = txtStartDate.Text.StringToDateAllowNull();
            manualLoan.EndDate = txtEndDate.Text.StringToDateAllowNull();
            manualLoan.LastPayDate = txtLastPayDate.Text.StringToDateAllowNull();
            manualLoan.NextPayDate = txtNextPayDate.Text.StringToDateAllowNull();
            manualLoan.PaymentFreq = txtPaymentFreq.Text.AsDecimal();
            manualLoan.PaymentFreqTimeBase= ddlPaymentFreqTimeBase.SelectedValue;
            manualLoan.PaymentConditionID = ddlPaymentCondition.SelectedValue.AsIntIsnull();
            manualLoan.CalInterestCondID = ddlCalInterestCond.SelectedValue.AsIntIsnull();                       
            manualLoan.InterestTypeID= ddlInterestType.SelectedValue.AsInt32();
            manualLoan.InterestRate= txtInterestRate.Text.AsDecimal();
            manualLoan.RefInterestCode= hidReferenceInterestCD.Value;
            manualLoan.AdditionalInterest= txtAdditionalInterest.Text.AsDecimal();
            manualLoan.DayCountMethodID = ddlDayCountMethod.Text.AsIntIsnull();                      
            manualLoan.CurrencyCode= txtCurrencyCode.Text;
            manualLoan.UnpaidInterest= txtUnpaidInterest.Text.AsDecimal();
            manualLoan.Dept= txtDept.Text.AsDecimal().Value;
            manualLoan.CreditLevelID= ddlCreditLevel.Text.AsInt32();
            manualLoan.CustomerID= hidCustomer.Value.AsInt32();
            manualLoan.ContractLoanTypeID= ddlContractLoanType.Text.AsInt32();
            manualLoan.LoanObjectiveID= hidLoanObjective.Value;
            manualLoan.FisrtMisDate = txtFirstMisDate.Text.StringToDateAllowNull();
            manualLoan.AdjustFlag = chkAdjustFlag.Checked == true ? "Y" : "";
            manualLoan.ReservedAmount= txtReservedAmount.Text.AsDecimal();
            manualLoan.ApprovedAmount= txtApprovedAmount.Text.AsDecimal();            
            manualLoan.RP_GSB_PRDCD = DefaultValue.RP_GSB_PRDCD.Corp_LN;
            manualLoan.RP_SOURCE_FILE = DefaultValue.RP_SOURCE_FILE.MANUAL_Corp_LN;
            manualLoan.RP_MAPPING_CD = DefaultValue.RP_MAPPING_CD.Corp_LN;
            manualLoan.IsConfirmed = false;     // 0 - สร้างรายการ, 1 - ยืนยัน
            manualLoan.SetStandardField();
          
            int iID = new SPR_MANUAL_LOAN().INSERT(manualLoan);

            if (iID > 0)
            {
                if (SaveNew)
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(Request.Url.AbsolutePath));
                }
                else
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(string.Format("~/IFRS/WIN02_2E.aspx?&id={0}", iID)));
                }
            }
            else
            {
                if (iID == -1)
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.Duplicate);
                }
                else
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.CanNotSaveData);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void ViewMenu()
    {
        MenuTitleBar = Resources.ifrsMenu.WIN02_4A;
    }
    #endregion
}